/*
    Copyright is LuoYuShun to 2022-2022
*/
package cn.com.laya.service.fourdemo.deals.websocket.impl;

import cn.com.laya.service.fourdemo.bean.ResultResponse;
import cn.com.laya.service.fourdemo.bean.WebSocketMessage;
import cn.com.laya.service.fourdemo.deals.websocket.WebSocketMessageHandler;
import cn.com.laya.service.fourdemo.enums.MessageTypeEnum;
import cn.com.laya.service.fourdemo.utils.WebSocketUtils;
import cn.com.laya.service.fourdemo.websocket.WebSocket;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * 初始化程序处理信息
 *
 * @author LuoYuShun
 * @since 2022-11-24
 */
@Component
@Slf4j
public class InitWebSocketMessageHandler extends WebSocketMessageHandler {
    @Override
    protected boolean isHandler(String messageType) {
        return MessageTypeEnum.INITDATA.getType().equals(messageType);
    }

    @Override
    protected void handlerMessage(WebSocketMessage webSocketMessage, Consumer<ResultResponse<?>> fallBackInvoke) {
        // 这里是要进行初始化数据的，其中包含了其他的场景等信息的更新
        List<WebSocketMessage> webSocketMessages = new ArrayList<>(300);
        List<WebSocketMessage> headImg = WebSocketUtils.getWebSocketMessageHeadImg(webSocketMessage.getScenario());
        // 头像图片为空不进行添加，否则进行添加
        if (!CollectionUtils.isEmpty(headImg)) {
            webSocketMessages.addAll(headImg);
        }
        List<WebSocketMessage> position = WebSocketUtils.getWebSocketMessagePosition(webSocketMessage.getScenario());
        // 如果位置的不为空，那么就进行添加，否则不添加
        if (!CollectionUtils.isEmpty(position)) {
            webSocketMessages.addAll(position);
        }
        List<WebSocketMessage> rotation = WebSocketUtils.getWebSocketMessageRotation(webSocketMessage.getScenario());
        // 如果旋转的集合不为空，那么就进行添加，否则不添加
        if (!CollectionUtils.isEmpty(rotation)) {
            webSocketMessages.addAll(rotation);
        }
        WebSocket webSocket = WebSocketUtils.getWebSocket(webSocketMessage.getAccount());
        ResultResponse<?> resultResponse;
        if (Objects.nonNull(webSocket)) {
            webSocket.setScenario(webSocketMessage.getScenario());
            WebSocketUtils.sendMessage(JSON.toJSONString(webSocketMessages), webSocket);
            resultResponse = ResultResponse.success("发送成功了");
        } else {
            log.error("该账号没有进行登录，请先登录！");
            resultResponse = ResultResponse.authError("该账号没有进行登录，请先登录");
        }
        // 判断回调是否为空，如果不为空，那么就进行调用，如果为空，那么就不能进行调用了。
        if (Objects.nonNull(fallBackInvoke)) {
            fallBackInvoke.accept(resultResponse);
        }
    }
}
